package edu.cuit.zhuyimeng.framework.swagger.config;

import edu.cuit.zhuyimeng.framework.common.property.SecurityProperties;
import edu.cuit.zhuyimeng.framework.swagger.property.SwaggerProperties;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Swagger文档配置类
 */
@AutoConfiguration
@RequiredArgsConstructor
@ConditionalOnClass({DispatcherServlet.class, Operation.class, OpenAPI.class})
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {

    private final SwaggerProperties swaggerProperties;

    @Bean
    public OpenAPI openAPI(@Autowired(required = false) SecurityProperties securityProperties) {
        OpenAPI openAPI = new OpenAPI();
        if (securityProperties != null) {
            openAPI.components(new Components()
                    .addSecuritySchemes(securityProperties.getTokenName(), new SecurityScheme()
                            .type(SecurityScheme.Type.HTTP)
                            .bearerFormat("JWT")
                            .scheme("bearer")));
        }
        return openAPI.info(new Info()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .license(new License()
                        .name(swaggerProperties.getLicense())
                        .url(swaggerProperties.getLicenseUrl()))
                .contact(new Contact()
                        .name(swaggerProperties.getConcat())
                        .email(swaggerProperties.getEmail())));

    }

}
